﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VibratorTool : MonoSingleton<VibratorTool>
{
    AndroidJavaClass jc;
    AndroidJavaObject jo;
    
    public bool VibrateState { get; private set; }
    private int _needVivrate = 0;
    //震动间隔帧数
    private const int _vibrateInterval = 2;
    //震动时长
    private long _time = 60;

    private void Awake()
    {
        LoadVibatorState();
        IniAnroid();
        _needVivrate = 0;
    }

    void IniAnroid()
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        if (jo == null)
        {
            jc = new AndroidJavaClass("com.plugins.unity.vibrator.VibratorActivity");
            jo = jc.CallStatic<AndroidJavaObject>("getInstance", "Main");
        }
#endif
    }

    public void StartVibrator()
    {
        if (!VibrateState)
        {
            return;
        }
        if (_needVivrate > 0)
        {
            return;
        }
        _needVivrate = _vibrateInterval;
    }

    private void SetVibrator()
    {
#if UNITY_ANDROID && !UNITY_EDITOR
            IniAnroid();
            jo.Call("StartShock", _time, 5);
#endif
    }

    private void Update()
    {
        if (_needVivrate > 0)
        {
            if (_needVivrate == _vibrateInterval)
            {
                SetVibrator();
            }
            _needVivrate --;
        }
    }

    public void SetVibatorState(bool state)
    {
        VibrateState = state;
        SaveVibatorState();
    }

    private const string key_VibatorState = "key_VibatorState";
    private void LoadVibatorState()
    {
        VibrateState = PlayerPrefs.GetInt(key_VibatorState, 1) == 1;
    }
    private void SaveVibatorState()
    {
        PlayerPrefs.SetInt(key_VibatorState, VibrateState ? 1 : 0);
    }

}
